﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Infinity.Expressions
{
	public partial class BlockBuilder : ICollection<Expression>
	{
		protected BlockExpression BlockExpression { get; set; }

		public BlockBuilder()
		{
			Clear();
		}

		public void Add(Expression item)
		{
			var listExpression = BlockExpression.Expressions.ToList();
			listExpression.Add(item);
			BlockExpression = Expression.Block(BlockExpression.Variables, listExpression);
		}

		public void Clear()
		{
			BlockExpression = Expression.Block(Expression.Empty());
		}

		public bool Contains(Expression item)
		{
			return BlockExpression.Expressions.Contains(item);
		}

		public void CopyTo(Expression[] array, int arrayIndex)
		{
			throw new NotImplementedException();
		}

		public int Count
		{
			get { return BlockExpression.Expressions.Count; }
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public bool Remove(Expression item)
		{
			var listExpression = BlockExpression.Expressions.ToList();
			bool succeed = listExpression.Remove(item);

			BlockExpression = Expression.Block(BlockExpression.Variables, listExpression);

			return succeed;
		}

		public IEnumerator<Expression> GetEnumerator()
		{
			return BlockExpression.Expressions.GetEnumerator();
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return BlockExpression.Expressions.GetEnumerator();
		}
	}
}
